import React, { useState, useEffect } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { toast } from 'sonner';
import TaskForm from '@/components/project/task-form';

const TaskFormPage = () => {
  const navigate = useNavigate();
  const { id } = useParams();
  const [searchParams] = useSearchParams();
  const projectId = searchParams.get('projectId');
  
  const [task, setTask] = useState(null);
  const [projects, setProjects] = useState([]);
  const [loading, setLoading] = useState(false);

  // 获取任务详情（编辑模式）
  useEffect(() => {
    if (id) {
      fetchTaskDetail();
    }
  }, [id]);

  // 获取项目列表
  useEffect(() => {
    fetchProjects();
  }, []);

  const fetchTaskDetail = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 模拟任务数据
      const mockTask = {
        id: parseInt(id),
        task_code: 'TASK-001',
        task_name: '需求分析',
        project_id: 1,
        description: '分析用户需求，制定功能规格说明书',
        assignee_name: '张三',
        participants: ['李四', '王五'],
        start_date: '2024-01-15',
        end_date: '2024-01-25',
        estimated_hours: 40,
        actual_hours: 35,
        status: '已完成',
        priority: '高',
        progress_percentage: 100,
        predecessor_tasks: [],
        successor_tasks: ['TASK-002', 'TASK-003'],
        remarks: '已完成需求调研和文档编写'
      };
      
      setTask(mockTask);
    } catch (error) {
      toast.error('获取任务详情失败');
      console.error('获取任务详情失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchProjects = async () => {
    try {
      // 模拟项目数据
      const mockProjects = [
        { id: 1, project_name: '电商平台开发项目' },
        { id: 2, project_name: '客户管理系统升级' },
        { id: 3, project_name: '移动端APP开发' }
      ];
      setProjects(mockProjects);
    } catch (error) {
      console.error('获取项目列表失败:', error);
    }
  };

  const handleSubmit = async (formData) => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      if (id) {
        // 更新任务
        console.log('更新任务:', formData);
        toast.success('任务更新成功');
      } else {
        // 创建任务
        console.log('创建任务:', formData);
        toast.success('任务创建成功');
      }
      
      // 如果有项目ID参数，返回到该项目的任务列表
      if (projectId) {
        navigate(`/project-management/task-management?projectId=${projectId}`);
      } else {
        navigate('/project-management/task-management');
      }
    } catch (error) {
      toast.error('保存失败');
      console.error('保存任务失败:', error);
    }
  };

  const handleCancel = () => {
    // 如果有项目ID参数，返回到该项目的任务列表
    if (projectId) {
      navigate(`/project-management/task-management?projectId=${projectId}`);
    } else {
      navigate('/project-management/task-management');
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="flex items-center gap-2">
          <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
          <span>加载中...</span>
        </div>
      </div>
    );
  }

  return (
    <TaskForm
      task={task}
      projects={projects}
      onSubmit={handleSubmit}
      onCancel={handleCancel}
    />
  );
};

export default TaskFormPage; 